package com.bcx.wind.workflow.mybatis;

import com.bcx.wind.workflow.access.paging.PagingBuilder;
import com.bcx.wind.workflow.db.tran.WindTransactionManager;
import com.bcx.wind.workflow.jdbc.JdbcAccess;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Mybatis 持久层处理器
 *
 * @author zhanglei
 */
public class MybatisAccess extends JdbcAccess {

    private SqlSessionFactory sqlSessionFactory;


    public MybatisAccess(DataSource dataSource) {
        super(dataSource);
    }

    public MybatisAccess(SqlSessionFactory sqlSessionFactory){
        this.sqlSessionFactory = sqlSessionFactory;
        this.dataSource = sqlSessionFactory.getConfiguration().getEnvironment().getDataSource();
        this.paging = PagingBuilder.buildPaging(getConnection());
        this.initDB(getConnection());
    }



    @Override
    public synchronized Connection getConnection() {
        if(this.sqlSessionFactory ==null){
            return super.getConnection();
        }
        Connection connection = windTransactionManager.getConnection();
        if(connection == null){
            try {
                connection = this.dataSource.getConnection();
                windTransactionManager.setConnection(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }
}
